package com.xiliubit.cloudpicture.manager;

import com.qcloud.cos.model.DeleteObjectsRequest;
import com.xiliubit.cloudpicture.config.CosClientConfig;
import com.xiliubit.cloudpicture.model.entity.Picture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PictureDeleteManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 删除图片列表
     *
     * @param pictureList
     */
    public void deletePictureList(List<Picture> pictureList){
        // Bucket 的命名格式为 BucketName-APPID ，此处填写的存储桶名称必须为此格式
        String bucketName = cosClientConfig.getBucket();
        // 指定被删除的文件在 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示删除位于 folder 路径下的文件 picture.jpg
        String host = cosClientConfig.getHost();
        ArrayList<DeleteObjectsRequest.KeyVersion> collect = new ArrayList<>();
        pictureList.forEach(picture -> {
            String url = picture.getUrl();
            String thumbnailUrl = picture.getThumbnailUrl();
            String webpKey = url.substring(host.length() + 1);
            String thumbnailKey = thumbnailUrl.substring(host.length() + 1);
            collect.add(new DeleteObjectsRequest.KeyVersion(webpKey));
            collect.add(new DeleteObjectsRequest.KeyVersion(thumbnailKey));
        });
        cosManager.deleteObjectList(collect);
    }
}
